package com.seeyon.apps.kk.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.Vector;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.seeyon.ctp.common.SystemEnvironment;

public class SFtpHandler {

	private static final Log log = LogFactory.getLog(SFtpHandler.class);
	private static final String inbound = "/WORKDAY_CHNOutbound_Wilma_WG00321/inbound";
	private static final String done = "/WORKDAY_CHNOutbound_Wilma_WG00321/done";
	private static final String start = "chn_demographic_data_";
	private static final String end = ".csv";
	private static String host;
	private static String username;
	private static String password;
	private static int port;
	private static SFtpHandler instance = null;
	private Session session = null;
	private static ChannelSftp sftp = null;
	private static FileOutputStream fileOutputStream = null;
	
	private SFtpHandler(){
	}
	
	public SFtpHandler(String host, int port, String username, String password) {
			this.host = host;
			this.port = port;
			this.username = username;
			this.password = password;
			instance = new SFtpHandler();
			sftp = instance.getChannel(60*1000);   //获取连接
	}
		
	public ChannelSftp getChannel(int timeout) {

		try{
	        JSch jsch = new JSch(); // 创建JSch对象
	        session = jsch.getSession(username, host, port); // 根据用户名，主机ip，端口获取一个Session对象
	        if (password != null) {
	            session.setPassword(password); // 设置密码
	        }
	        Properties config = new Properties();
	        config.put("StrictHostKeyChecking", "no");
	        session.setConfig(config); // 为Session对象设置properties
	        session.setTimeout(timeout); // 设置timeout时间
	        session.connect(); // 通过Session建立链接
	
	        Channel channel = session.openChannel("sftp"); // 打开SFTP通道
	        channel.connect(); // 建立SFTP通道的连接
	        return (ChannelSftp) channel;
		} catch(JSchException e){
			log.error("##强生客开: ftp连接失败", e);
			try {
				instance.closeChannel();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				log.error("##强生客开: ftp连接失败", e);
			}
			return null;
		}
    }
	private List<LsEntry> getCurrentDateFile(String path) throws SftpException{
		List<LsEntry> list = new ArrayList<ChannelSftp.LsEntry>();
		Vector<LsEntry> files = sftp.ls(path);
		sftp.cd(path);
		
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_YEAR, -1);
//		String dateStr = DateUtil.format(cal.getTime(), "yyyyMMdd");
		for(LsEntry file : files){
			String fileName = file.getFilename().toLowerCase();
			if(fileName.endsWith(end)
					&& fileName.startsWith(start)){//+dateStr)){
				list.add(file);
			}
		}
		return list;
	}
	
	public File getFile(){
		try {
			List<LsEntry> list = getCurrentDateFile(inbound);
			if(CollectionUtils.isEmpty(list)){
				list = getCurrentDateFile(done);
			}
			if(CollectionUtils.isEmpty(list)){
				return null;
			} else if(list.size() > 1) {
				list.sort(new Comparator<LsEntry>(){
					@Override
					public int compare(LsEntry o1, LsEntry o2) {
						// TODO Auto-generated method stub
						try {
							SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
							Date date1 = (Date) format.parse(o1.getAttrs().getMtimeString());
							Date date2 = (Date) format.parse(o2.getAttrs().getMtimeString());
							return date2.compareTo(date1);
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							log.error("##强生客开: ftp下载文件按日期排序异常", e);
						}
						return 0;
					}
				});
			}
			
			String path = SystemEnvironment.getApplicationFolder().split("ApacheJetspeed")[0].replaceAll("\\\\", "/")
					+ "base/synMember" ;
			LsEntry file = list.get(0);
			File localFile = new File(path);
			if(!localFile.exists()){
				localFile.mkdirs();
			} else {
				File[] localFiles = localFile.listFiles();
				List<File> listFile = Arrays.asList(localFiles);
				for(File historyFile : listFile){
					historyFile.delete();
				}
			}
			localFile = new File(path + File.separator + file.getFilename());
			fileOutputStream = new FileOutputStream(localFile);
            sftp.get(file.getFilename(), fileOutputStream);
            return localFile;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			log.error("##强生客开: ftp下载失败", e);
		} catch (SftpException e) {
			// TODO Auto-generated catch block
			log.error("##强生客开: ftp下载失败", e);
		} finally {
			try {
				if(fileOutputStream != null){
					fileOutputStream.close();
				}
				instance.closeChannel();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				log.error("##强生客开: ftp关闭连接失败", e);
			}
		}
		return null;
	}

    public void closeChannel() throws Exception {
    	if (session != null) {
    		session.disconnect();
    	}
        if (sftp != null) {
        	sftp.disconnect();
        }
    }
    
}
